﻿#if UNITY_EDITOR

using System;
using System.Collections;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

public class EditorAssetsLoadManager
{
    public static bool SimulatorAssetsLoad {
        get {
            return EditorPrefs.GetBool("key_SimulatorAssetsLoad", false);
        }
        set {
            EditorPrefs.SetBool("key_SimulatorAssetsLoad", value);
        }
    }

    [MenuItem("Custom/AssetBundle/SimulatorAssetsLoad")]
    public static bool CheckSimulatorAssetsLoad()
    {
        bool bSimulator = SimulatorAssetsLoad;
        SimulatorAssetsLoad = !bSimulator;
        Debug.LogFormat("Simulator assets load enable: {0}", !bSimulator);
        return true;
    }

    public static T LoadAsset<T>(string bundleName, string assetName) 
        where T : UnityEngine.Object
    {
        string[] assets = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(bundleName, assetName);
        for(int i=0; i<assets.Length; i++) {
            string filename = assets[i];
            if (filename.Contains(assetName)) {
                return AssetDatabase.LoadAssetAtPath<T>(filename);
            }
        }
        return null;
    }

    public static UnityEngine.Object[] LoadAllBundleAsync(string bundleName)
    {
        string[] files = AssetDatabase.GetAssetPathsFromAssetBundle(bundleName);
        UnityEngine.Object[] assets = new UnityEngine.Object[files.Length];
        for(int i=0; i<files.Length; i++) {
            assets[i] = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(files[i]);
        }
        return assets;
    }

    private static string GetScenePath(string bundleName, string sceneName)
    {
        string[] assets = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(bundleName, sceneName);
        sceneName = string.Format("{0}.unity", sceneName);
        for(int i=0; i<assets.Length; i++) {
            if (assets[i].Contains(sceneName)) {
                return assets[i];
            }
        }
        return null;
    }

    public static IEnumerator LoadSceneCoroutine(string bundleName, string sceneName, bool additive, Action<AsyncOperation> OnLoadCallback)
    {
        sceneName = GetScenePath(bundleName, sceneName);
        if (string.IsNullOrEmpty(sceneName)) {
            Debug.LogErrorFormat("None scene in AssetBundle: {0}, name is:{1}.", bundleName, sceneName);
            yield return null;
        } else {
            yield return new WaitForSeconds(0.5f);
            LoadSceneParameters loadParams = new LoadSceneParameters(additive ? LoadSceneMode.Additive : LoadSceneMode.Single);
            AsyncOperation asy = EditorSceneManager.LoadSceneAsyncInPlayMode(sceneName, loadParams);
            while (!asy.isDone && null != OnLoadCallback) {
                OnLoadCallback?.Invoke(asy);
                yield return asy;
            }
            OnLoadCallback?.Invoke(asy);
        }
    }
}

#endif